import datetime
import wsgiref.handlers
import statsdb
import statsdt

from google.appengine.ext import webapp
from google.appengine.ext import db
import gviz_api

class QueryStats(webapp.RequestHandler):
  def get(self):
    # We use the webapp framework to retrieve the keyword
    tags = self.request.get('tags').split(' ')
    if 0 == len(self.request.get('begin')):
      begin = datetime.datetime.strptime("197001010000", "%Y%m%d%H%M%S")
    else:
      begin = datetime.datetime.strptime(self.request.get('begin'), "%Y%m%d%H%M%S")
    if 0 == len(self.request.get('end')):
      end = datetime.datetime.now()
    else:
      end = datetime.datetime.strptime(self.request.get('end'), "%Y%m%d%H%M%S")
    datefmt = str(self.request.get('dfmt'))
    x = str(self.request.get('x')).split(' ')
    y = str(self.request.get('y')).split(' ')
    #Get request tqx for response
    tqx = self.request.get('tqx')
    reqId = 0
    if tqx:
      params = dict([p.split(':') for p in tqx.split(';')])
      reqId = params['reqId']
    
    self.response.headers['Content-Type'] = 'text/plain'
    results = statsdb.Record.gql("WHERE date >= :1 and date <=:2 and tags = :3", 
                                 begin, end, tags)
    if 0 == results.count():
      self.response.out.write("google.visualization.Query.setResponse({version:'0.5',reqId:'"+str(reqId)+"',status:'error',errors:[{reason:'invalid_query',message:'Invalid query',detailed_message:'No data found.'}]});")
      self.updateHistory(tags, False)
      return;

    dtParams = [{}, {}, []] #columns, rows, column order    
    #Use default StatsDT class
    dtStats = self.getDTStats(results, x, y)
    dtStats.fill(dtParams, results, tags, datefmt, x, y)

    data_table = gviz_api.DataTable(dtParams[0])
    data_table.AppendData(dtParams[1])
    self.response.out.write(data_table.ToJSonResponse(
          columns_order = dtParams[2],
          order_by = dtParams[2][0],
          req_id = reqId))
    self.updateHistory(tags)
  
  def getDTStats(self, results, x, y):
    if 0 == len("".join(x)) and 0 == len("".join(y)):
      return statsdt.DTX()
    if "date" in x:
      return statsdt.DTX()
    if "date" in y:
      return statsdt.DTY()
    if not "date" in x and not "date" in y:
      return statsdt.DTTags()
    # More conditions later    
    return statsdt.BaseStatsDT() #default

  def updateHistory(self, tags, found = True):
    results = statsdb.History.gql("WHERE tags = :1", tags)
    for history in results:
      if len(history.tags) == len(tags):
        history.qcount += 1
        history.found = found
        history.put()
        return
    history = statsdb.History()
    history.tags = tags
    history.found = found
    history.put()
  
class QueryTags(webapp.RequestHandler):
  def get(self):
    #Get request tqx for response
    tqx = self.request.get('tqx')
    reqId = 0
    if tqx:
      params = dict([p.split(':') for p in tqx.split(';')])
      reqId = params['reqId']
    
    self.response.headers['Content-Type'] = 'text/plain'
    results = statsdb.Tags.all()
    
    dtParams = [[], [], []] #columns, rows, column order
    dtParams[0] = [('name', 'string'),('refCount', 'number')]
    for tag in results:
      dtParams[1].append([tag.name, tag.refCount])
    dtParams[2] = ['name', 'refCount'] 
    
    data_table = gviz_api.DataTable(dtParams[0])
    data_table.AppendData(dtParams[1])
    self.response.out.write(data_table.ToJSonResponse(
          columns_order = dtParams[2],
          order_by = dtParams[2][0],
          req_id = reqId))

class QueryHistory(webapp.RequestHandler):
  def get(self):
    #Get request tqx for response
    tqx = self.request.get('tqx')
    reqId = 0
    if tqx:
      params = dict([p.split(':') for p in tqx.split(';')])
      reqId = params['reqId']
    found = True
    if "false" == self.request.get('found'):
      found = False
    
    self.response.headers['Content-Type'] = 'text/plain'
    results = statsdb.History.gql("WHERE found = :1 ORDER BY qcount ASC", found)
    results.fetch(20)
    
    dtParams = [[], [], []] #columns, rows, column order
    dtParams[0] = [('tags', 'string'),('qcount', 'number')]
    for history in results:
      dtParams[1].append([" ".join(history.tags), history.qcount]) #use space as seperator for GWT SuggestBox
    dtParams[2] = ['tags', 'qcount'] 
    
    data_table = gviz_api.DataTable(dtParams[0])
    data_table.AppendData(dtParams[1])
    self.response.out.write(data_table.ToJSonResponse(
          columns_order = dtParams[2],
          order_by = dtParams[2][0],
          req_id = reqId))


def main():
  application = webapp.WSGIApplication([('/querystats', QueryStats),
                                        ('/querytags', QueryTags),
                                        ('/queryhistory', QueryHistory)],
                                       debug=True)
  wsgiref.handlers.CGIHandler().run(application)

if __name__ == "__main__":
  main()
